<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

const router = useRouter();
const authStore = useAuthStore();

const email = ref('');
const password = ref('');
const isLoading = ref(false);
const errorMessage = ref('');

async function handleLogin() {
  if (!email.value || !password.value) {
    errorMessage.value = '请输入邮箱和密码';
    return;
  }

  isLoading.value = true;
  errorMessage.value = '';

  try {
    await authStore.login(email.value, password.value);

    // 登录成功，跳转到首页
    router.push('/');
  } catch (error) {
    console.error('登录失败:', error);
    errorMessage.value = '登录失败，请重试';
  } finally {
    isLoading.value = false;
  }
}

// 处理Enter键事件
function handleKeyup(event: KeyboardEvent) {
  if (event.key === 'Enter' && !isLoading.value) {
    handleLogin();
  }
}
</script>

<template>
  <div class="min-h-screen flex items-center justify-center bg-gray-50">
    <Card class="w-full max-w-sm">
      <CardHeader>
        <CardTitle class="text-2xl">
          登录
        </CardTitle>
        <CardDescription>
          请输入您的邮箱和密码登录账户
        </CardDescription>
      </CardHeader>
      <CardContent class="grid gap-4">
        <div v-if="errorMessage" class="text-red-500 text-sm">
          {{ errorMessage }}
        </div>
        <div class="grid gap-2">
          <Label for="email">邮箱</Label>
          <Input
            id="email"
            v-model="email"
            type="email"
            placeholder="m@example.com"
            required
            @keyup="handleKeyup"
          />
        </div>
        <div class="grid gap-2">
          <Label for="password">密码</Label>
          <Input
            id="password"
            v-model="password"
            type="password"
            required
            @keyup="handleKeyup"
          />
        </div>
      </CardContent>
      <CardFooter>
        <Button
          class="w-full"
          :disabled="isLoading"
          @click="handleLogin"
        >
          {{ isLoading ? '登录中...' : '登录' }}
        </Button>
      </CardFooter>
    </Card>
  </div>
</template>
